//
//  YWDownloadController.m
//  videoTest3
//
//  Created by jun peng on 2022/7/13.
//

#import "YWDownloadController.h"
#import "YWYoukuDetailController.h"

#import "YWKLineCheatsVideoListParam.h"
#import "YWKLineCheatsVideoListStatus.h"
#import "YWKLineCheatsVideoListResultStatus.h"
#import "YWKLineCheatsVideoListPageStatus.h"
#import "YWKLineCheatsVideoListDataStatus.h"
#import "YWKLineCheatsVideoListTool.h"
//#import "YWKLineCheatsClassCell.h"
#import "YWDownloadCell.h"
#import "YWDownloadStatus.h"
#import "YWDownloadDataTaskStatus.h"
#import "YWDownloadManager.h"

#import "YWNoContentView2.h"
#import "YWSectionGroupStatus.h"

@interface YWDownloadController ()<UITableViewDelegate,UITableViewDataSource,YWDownloadCellDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barConstraintHeight;
@property (weak, nonatomic) IBOutlet YWTableView *tableView;

@property (nonatomic,strong)NSMutableArray *group;
@end

@implementation YWDownloadController


-(NSMutableArray*)group{
    if (_group == nil) {
        _group = [NSMutableArray array];
        
        YWSectionGroupStatus *sectionStatus0 = [[YWSectionGroupStatus alloc] init];
        sectionStatus0.headerTitle = @"     正在下载";
        sectionStatus0.remark = 0;
//        sectionStatus1.statusArray = @[[YWDownloadStatus new]];
        
        YWSectionGroupStatus *sectionStatus1 = [[YWSectionGroupStatus alloc] init];
        sectionStatus1.headerTitle = @"     下载完成";
        sectionStatus1.remark = 1;
//        sectionStatus2.statusArray = @[[YWDownloadStatus new]];
        
        [_group addObject:sectionStatus0];
        [_group addObject:sectionStatus1];
        
    }
    return _group;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBar.title = @"下载列表";
    self.barConstraintHeight.constant = self.navBar.frame.size.height;
    
    //1、创建下载任务
    [self createDownloadDataTask];
    
    //2、获取下载任务列表
    [self loadLocalNewData];
    
    //3、添加通知
    [self addObserveNotification];
    
    [self setupRightItem];
}

//建立左边的item
-(void)setupLeftItem{
    
    UIButton *backBtn = [[UIButton alloc] init];
    [backBtn setImage:[UIImage imageNamed:@"icon-邮件认证"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"icon-邮件认证"] forState:UIControlStateHighlighted];
    backBtn.bounds = CGRectMake(0, 0, 100, 30);
    self.navBar.leftItem = backBtn;
    [backBtn addTarget:self action:@selector(askShow) forControlEvents:UIControlEventTouchUpInside];
    
    [backBtn setTitle:@"提示" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    [backBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 15, 0, 0)];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
}



-(void)setupRightItem{
    
    UIButton *rightItem = [[UIButton alloc] init];
    [rightItem setTitle:@"提示" forState:UIControlStateNormal];
    [rightItem setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightItem setImage:[UIImage imageNamed:@"icon-邮件认证"] forState:UIControlStateNormal];
    [rightItem setImage:[UIImage imageNamed:@"icon-邮件认证"] forState:UIControlStateHighlighted];
    rightItem.bounds = CGRectMake(0, 0, 100, 30);
    rightItem.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [rightItem setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
    [rightItem setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
    self.navBar.rightItem = rightItem;
    rightItem.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightItem addTarget:self action:@selector(askShow) forControlEvents:UIControlEventTouchUpInside];
}


-(void)askShow{
    
    YWAskView *askView = [YWAskView askView];
    
    askView.title = @"\n1、控制器VC：操作与显示模型数组：处理YWDownloadStatus的归档用来记录下载文件信息\n\n2、单例Manager：有一个字典用来装YWDownloadDataTaskStatus、用来规范下载任务、且是单例下载会App运行期间一直存在\n\n3、YWDownloadDataTaskStatus：每个独立下载个体、处理下载“自己”、把文件保存到沙盒与处理文件路径\n\n4、YWDownloadStatus：单个视频模型信息\n\n";
    [askView show];
    
}


//按cell的暂停继续按钮代理
-(void)downloadCell:(YWDownloadCell *)downloadCell didClickSituationBtnWithStatus:(YWDownloadStatus *)itemStatus{
    
    YWDownloadManager *manager = [YWDownloadManager sharedownloadManager];
    
    if (itemStatus.downloadType == YWDownloadType_Downloading) {
        [manager pauseOneDataTaskWithStatus:itemStatus];
    }
    else if (itemStatus.downloadType == YWDownloadType_Pause) {
        [manager continueOneDataTaskWithStatus:itemStatus];
    }
}

-(void)createDownloadDataTask{
    
    //可以先归档、再反归档获取本地所有数组、然后全部加入下载（假如正在下载中的任务你依然调用下载也不用怕因为里面做了假如有任务了就不会添加下载了）
    
   //1、先判断传入来的模型存不存在，不存在就不需要归档了
   if (self.downloadStatus != nil) {
       
       //2、先判断已经下载的文件夹存不存在这个传入来的模型的URL、假如存在了就不需要下载了
       BOOL isExistFinishDownload = NO;
       NSArray *finishDownloadStatusArray = [NSKeyedUnarchiver unarchiveObjectWithFile:YWFinishDownloadStatuspath];
       for (YWDownloadStatus *status in finishDownloadStatusArray) {
           if ([status.VideoUrl isEqualToString:self.downloadStatus.VideoUrl]) {
               isExistFinishDownload = YES;
               break;
           }
       }
       if (isExistFinishDownload == NO) {
           
           
           //3、再判断正在下载的文件夹存不存在这个传入来的模型的URL、假如存在了就不需要归档了
           BOOL isExistDownloading = NO;
           NSArray *downloadinigStatusArray = [NSKeyedUnarchiver unarchiveObjectWithFile:YWDownloadingStatuspath];
           for (YWDownloadStatus *status in downloadinigStatusArray) {
               if ([status.VideoUrl isEqualToString:self.downloadStatus.VideoUrl]) {
                   isExistDownloading = YES;
                   break;
               
               }
           }
           if (isExistDownloading == NO) {
               //4、假如不存在进行归档到正在下载的文件夹
               
               NSMutableArray *mArray = [NSMutableArray arrayWithArray:downloadinigStatusArray];
               
               YWDownloadStatus *dStatus = [[YWDownloadStatus alloc] init];
               
               
               dStatus.downloadType = YWDownloadType_Downloading;
               dStatus.Title = self.downloadStatus.Title;
               dStatus.PicUrl = self.downloadStatus.PicUrl;
               dStatus.Id = self.downloadStatus.Id;
               dStatus.VideoUrl = self.downloadStatus.VideoUrl;


               [mArray addObject:dStatus];
               
               downloadinigStatusArray = mArray;
               
               // 归档模型（保存到本地）
               [NSKeyedArchiver archiveRootObject:downloadinigStatusArray toFile:YWDownloadingStatuspath];
               
           }
          
           
       }
       
   }
   
   //5、反归档将所有正在下载的文件夹的文件拿出来全部都开启任务下载
   YWDownloadManager *manager = [YWDownloadManager sharedownloadManager];
   NSArray *downloadinigStatusArray = [NSKeyedUnarchiver unarchiveObjectWithFile:YWDownloadingStatuspath];
   [manager createDataTaskWithStatusArray:downloadinigStatusArray];
   
  
}

-(void)addObserveNotification{
    
    //手动开始/继续下载
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resumeDownloadNote:) name:YWResumeDownloadNote object:nil];
//    //手动暂停下载
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pauseDownloadNote:) name:YWPauseDownloadNote object:nil];
//    //手动移除下载
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeDownloadNote:) name:YWRemoveDownloadNote object:nil];
    
    //开始下载回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startDownloadNote:) name:YWStartDownloadNote object:nil];
    //正在下载回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(progressDownloadNote:) name:YWProgressDownloadNote object:nil];
    //完成下载回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishDownloadNote:) name:YWFinishDownloadNote object:nil];
    //下载失败回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(errorDownloadNote:) name:YWErrorDownloadNote object:nil];
}

//手动开始/继续下载
-(void)resumeDownloadNote:(NSNotification *)notification{
    
    //拿出模型
    YWDownloadStatus *status = notification.userInfo[@"YWDownloadStatusKey"];

    
    [self refreshLocalDataWithStatus:status];

}

//手动暂停下载
-(void)pauseDownloadNote:(NSNotification *)notification{
    
    //拿出模型
    YWDownloadStatus *status = notification.userInfo[@"YWDownloadStatusKey"];
    
   
    [self refreshLocalDataWithStatus:status];


}

//手动移除下载
-(void)removeDownloadNote:(NSNotification *)notification{
    
    //拿出模型
    YWDownloadStatus *status = notification.userInfo[@"YWDownloadStatusKey"];


}

//开始下载回调
-(void)startDownloadNote:(NSNotification *)notification{
    
    //拿出模型
    YWDownloadStatus *status = notification.userInfo[@"YWDownloadStatusKey"];

    //这里可以做刷新totalSize和currentSize了（对之前下载到一半但没继续下载现在看回之前的currentSize很有效）
    [self refreshLocalDataWithStatus:status];
}

//正在下载回调
-(void)progressDownloadNote:(NSNotification *)notification{
    
    //拿出模型
    YWDownloadStatus *status = notification.userInfo[@"YWDownloadStatusKey"];

//    [self refreshLocalDataWithStatus:status];
    
    
    YWSectionGroupStatus *sectionStatus0 = self.group[0];
    
    
//    sectionStatus0.statusArray = [NSMutableArray arrayWithArray:downloadinigStatusArray];
    
    NSMutableArray *downloadinigStatusArray = sectionStatus0.statusArray;
    
    NSInteger i = 0;
    for (YWDownloadStatus *downloadStatus in downloadinigStatusArray) {
        
        if ([downloadStatus.VideoUrl isEqualToString:status.VideoUrl]) {
            
            downloadStatus.currentSize = status.currentSize;
            
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            
            break;
        }
        
        i++;
    }
    
    
//    [self.tableView reloadData];
    
    
}

//完成下载回调
-(void)finishDownloadNote:(NSNotification *)notification{
    
    //拿出模型
    YWDownloadStatus *status = notification.userInfo[@"YWDownloadStatusKey"];
    
    
    NSArray *downloadinigStatusArray = [NSKeyedUnarchiver unarchiveObjectWithFile:YWDownloadingStatuspath];
    NSArray *finishDownloadStatusArray = [NSKeyedUnarchiver unarchiveObjectWithFile:YWFinishDownloadStatuspath];
    
    NSMutableArray *mDownloadinigStatusArray = [NSMutableArray arrayWithArray:downloadinigStatusArray];
    NSMutableArray *mfinishDownloadStatusArray = [NSMutableArray arrayWithArray:finishDownloadStatusArray];
    
    //倒叙删除正在下载数组的元素
     [mDownloadinigStatusArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
         
         YWDownloadStatus *downloadStatus = (YWDownloadStatus *)obj;

         if ([downloadStatus.VideoUrl isEqualToString:status.VideoUrl]){

             [mDownloadinigStatusArray removeObject:downloadStatus];
             *stop = YES;

         }
     }];
    
    downloadinigStatusArray = mDownloadinigStatusArray;
    
    // 归档模型（保存到本地）
    [NSKeyedArchiver archiveRootObject:downloadinigStatusArray toFile:YWDownloadingStatuspath];
    
    //归档到到完成数据
    [mfinishDownloadStatusArray addObject:status];
    
    // 归档模型（保存到本地）
    [NSKeyedArchiver archiveRootObject:mfinishDownloadStatusArray toFile:YWFinishDownloadStatuspath];
    
    //再一次刷新列表
    [self loadLocalNewData];

}

//下载失败回调
-(void)errorDownloadNote:(NSNotification *)notification{
    
    //拿出模型
    YWDownloadStatus *status = notification.userInfo[@"YWDownloadStatusKey"];

    [self refreshLocalDataWithStatus:status];
}


-(void)refreshLocalDataWithStatus:(YWDownloadStatus*)status{
    NSArray *downloadinigStatusArray = [NSKeyedUnarchiver unarchiveObjectWithFile:YWDownloadingStatuspath];
    
    NSMutableArray *mDownloadinigStatusArray = [NSMutableArray arrayWithArray:downloadinigStatusArray];
    
    //倒叙删除正在下载数组的元素
     [mDownloadinigStatusArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
         
         YWDownloadStatus *downloadStatus = (YWDownloadStatus *)obj;

         if ([downloadStatus.VideoUrl isEqualToString:status.VideoUrl]){

             [mDownloadinigStatusArray removeObject:downloadStatus];
             *stop = YES;

         }
     }];
    
    
    //归档到到完成数据
    [mDownloadinigStatusArray addObject:status];

    
    downloadinigStatusArray = mDownloadinigStatusArray;
    
    // 归档模型（保存到本地）
    [NSKeyedArchiver archiveRootObject:downloadinigStatusArray toFile:YWDownloadingStatuspath];
        
    //再一次刷新列表
    [self loadLocalNewData];
    
    
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
  


//获取本地数据
-(void)loadLocalNewData{
    
    NSArray *downloadinigStatusArray = [NSKeyedUnarchiver unarchiveObjectWithFile:YWDownloadingStatuspath];
    
    NSArray *finishDownloadStatusArray = [NSKeyedUnarchiver unarchiveObjectWithFile:YWFinishDownloadStatuspath];
    
    if (finishDownloadStatusArray.count == 0 && downloadinigStatusArray.count == 0) {
        
        //这里弄个noCotentView
        
        [self.view addSubview:self.noContentView];
        
        self.noContentView.frame = CGRectMake(0, self.navBar.height, Wi, self.view.height - self.navBar.height);
        
        self.noContentView.noContentType = YWNoContentView2Type_NoContentButNotConformBtn;
    }
    else{
        
        //移除noCotentView
        
          [self.noContentView removeFromSuperview];
        
        YWSectionGroupStatus *sectionStatus0 = self.group[0];
        YWSectionGroupStatus *sectionStatus1 = self.group[1];
        
        sectionStatus0.statusArray = [NSMutableArray arrayWithArray:downloadinigStatusArray];
        sectionStatus1.statusArray = [NSMutableArray arrayWithArray:finishDownloadStatusArray];
        
        
        [self.tableView reloadData];
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YWSectionGroupStatus *sectionStatus = self.group[indexPath.section];
    
    YWDownloadStatus *status = sectionStatus.statusArray[indexPath.row];
    
    YWDownloadCell *cell = [YWDownloadCell cellWithTableView:tableView];
    cell.delegate = self;
    cell.status = status;
    
    return cell;

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.group.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    YWSectionGroupStatus *group = self.group[section];
    return group.statusArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 105;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    YWSectionGroupStatus *scetionStatus = self.group[section];
    
    //没数据就不要头部了
    if (scetionStatus.statusArray.count == 0 ) {
        
        return 1;
    }
    else{
        
        return 30;
      
    }
    
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
 
    
    YWSectionGroupStatus *scetionStatus = self.group[section];
    
    //没数据就不要头部了
    if (scetionStatus.statusArray.count == 0 ) {
        
        return nil;
    }
    else{
        UILabel *label = [[UILabel alloc] init];
        label.text = scetionStatus.headerTitle;
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor blackColor];
        label.frame = CGRectMake(0, 0, Wi, 30);
        return label;
      
    }
    
}

@end
